import React, { useState, useCallback, useEffect, useMemo } from 'react';
import { connect } from 'react-redux';
import './App.css';
import Header from '../common/Header';
import Nav from '../common/Nav';
import List from './List';
import Bottom from './Bottom';
import Loading from './Loading';
import dayjs from 'dayjs';
import { h0 } from '../common/fp';
import {
  setFrom,
  setTo,
  setDepartDate,
  setHighSpeed,
  setSearchParsed,
  setTrainList,
  setTicketTypes,
  setTrainTypes,
  setDepartStations,
  setArriveStations,
  prevDay,
  nextDay,
  toggleHighSpeed,
  toggleIsFiltersVisible,
  toggleOnlyTickets,
  toggleOrderType,

  //综合筛选浮层用到的actions
  setCheckedTicketTypes,
  setCheckedTrainTypes,
  setCheckedDepartStations,
  setCheckedArriveStations,
  setDepartTimeStart,
  setDepartTimeEnd,
  setArriveTimeStart,
  setArriveTimeEnd,
} from './actions';
import URI from 'urijs';

//导入自定义函数useNav
import useNav from '../common/useNav';
import { bindActionCreators } from 'redux';
function App(props) {
  const {
    trainList,
    from,
    to,
    departDate,
    highSpeed, //只看高铁动车
    isFiltersVisible, //综合筛选是否可见
    orderType, //排序类型
    onlyTickets, //只看邮票
    searchParsed,
    ticketTypes, //坐席类型
    trainTypes, //车次类型
    departStations, //出发车站
    arriveStations, //到达车站
    checkedTicketTypes,
    checkedTrainTypes,
    checkedDepartStations,
    checkedArriveStations,
    departTimeStart,
    departTimeEnd,
    arriveTimeStart,
    arriveTimeEnd,
    dispatch,
  } = props;
  //默认没有数据,正在加载
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    const queries = URI.parseQuery(window.location.search);
    const { from, to, highSpeed, date } = queries;

    dispatch(setFrom(from));
    dispatch(setTo(to));
    dispatch(setDepartDate(h0(dayjs(date).valueOf())));
    dispatch(setHighSpeed('true' === highSpeed));
    dispatch(setSearchParsed(true));
  }, [dispatch]);
  //定义获取到查询条件后,才发起异步请求获取车次信息数据
  useEffect(() => {
    if (!searchParsed) {
      return; //没有解析完成 不发起异步请求
    }
    setLoading(true);
    new Promise((resolve) => {
      let delay = Math.floor(Math.random() * 1000); //[0-999]
      setTimeout(() => {
        resolve();
      }, 500 + delay);
    }).then(() => {
      const url = new URI('/rest/query')
        .setSearch('from', from)
        .setSearch('to', to)
        .setSearch('departDate', departDate)
        .setSearch('highSpeed', highSpeed)
        .setSearch('orderType', orderType)
        .setSearch('onlyTickets', onlyTickets)
        //对于对象的参数只要key存在,就说明key对应项被选中了 join函数默认添加分隔符,
        .setSearch('checkedTicketTypes', Object.keys(checkedTicketTypes).join())
        .setSearch('checkedTrainTypes', Object.keys(checkedTrainTypes).join())
        .setSearch(
          'checkedDepartStations',
          Object.keys(checkedDepartStations).join()
        )
        .setSearch(
          'checkedArriveStations',
          Object.keys(checkedArriveStations).join()
        )
        .setSearch('departTimeStart', departTimeStart)
        .setSearch('departTimeEnd', departTimeEnd)
        .setSearch('arriveTimeStart', arriveTimeStart)
        .setSearch('arriveTimeEnd', arriveTimeEnd)
        .toString();

      fetch(url)
        .then((res) => res.json())
        .then((result) => {
          const {
            dataMap: {
              directTrainInfo: {
                trains,
                filter: { ticketType, trainType, depStation, arrStation },
              },
            },
          } = result;
          setLoading(false);
          dispatch(setTrainList(trains));
          dispatch(setTicketTypes(ticketType));
          dispatch(setTrainTypes(trainType));
          dispatch(setDepartStations(depStation));
          dispatch(setArriveStations(arrStation));
        });
    });
  }, [
    arriveTimeEnd,
    arriveTimeStart,
    checkedArriveStations,
    checkedDepartStations,
    checkedTicketTypes,
    checkedTrainTypes,
    departDate,
    departTimeEnd,
    departTimeStart,
    dispatch,
    from,
    highSpeed,
    onlyTickets,
    orderType,
    searchParsed,
    to,
  ]);
  const onBack = useCallback(() => {
    window.history.go(-1);
  }, []);
  // //出发日期少于今天  前一天不可点击
  // const isPrevDisable = h0(departDate) - h0() <= 0
  // //当出发日期 超过20天外  后一天不可点击
  // const isNextDisable = h0(departDate) - h0() >= 20 * 24 * 3600 * 1000

  // const prev = () => {
  //   if (isPrevDisable) {
  //     return
  //   }
  //   dispatch(prevDay())
  // }
  // const next = () => {
  //   if (isNextDisable) { return }
  //   dispatch(nextDay())
  // }

  //自定义hook函数
  const { isPrevDisable, isNextDisable, prev, next } = useNav(
    departDate,
    dispatch,
    prevDay,
    nextDay
  );

  const bottomCbs = useMemo(() => {
    return bindActionCreators(
      {
        toggleHighSpeed,
        toggleIsFiltersVisible,
        toggleOnlyTickets,
        toggleOrderType,
        //综合浮层相关
        setCheckedTicketTypes,
        setCheckedTrainTypes,
        setCheckedDepartStations,
        setCheckedArriveStations,
        setDepartTimeStart,
        setDepartTimeEnd,
        setArriveTimeStart,
        setArriveTimeEnd,
      },
      dispatch
    );
  }, [dispatch]);
  return (
    <div>
      <div className="header-wrapper">
        <Header title={`${from} ⇀ ${to}`} onBack={onBack} />
      </div>
      <div className="scroll-content">
        <Nav
          date={departDate}
          prev={prev}
          next={next}
          isNextDisabled={isNextDisable}
          isPrevDisabled={isPrevDisable}
        />
        <List list={trainList} />
      </div>
      {loading && <Loading />}
      <Bottom
        {...bottomCbs}
        highSpeed={highSpeed}
        orderType={orderType}
        onlyTickets={onlyTickets}
        isFilterVisible={isFiltersVisible}
        ticketTypes={ticketTypes} //坐席类型
        trainTypes={trainTypes} //车次类型
        departStations={departStations} //出发车站
        arriveStations={arriveStations} //到达车站
        checkedTicketTypes={checkedTicketTypes}
        checkedTrainTypes={checkedTrainTypes}
        checkedDepartStations={checkedDepartStations}
        checkedArriveStations={checkedArriveStations}
        departTimeStart={departTimeStart}
        departTimeEnd={departTimeEnd}
        arriveTimeStart={arriveTimeStart}
        arriveTimeEnd={arriveTimeEnd}
      />
    </div>
  );
}

const mapStateToProps = (state) => {
  return state;
};

const mapDispatchToProps = (dispatch) => {
  return { dispatch };
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
